package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    _ "github.com/mattn/go-sqlite3"
)

type GameRecord struct {
    Username   string `json:"username"`
    Score      int    `json:"score"`
    Difficulty int    `json:"difficulty"`
    Time       string `json:"time"`
}

var db *sql.DB

func initDB() {
    var err error
    db, err = sql.Open("sqlite3", "./game_records.db")
    if err != nil {
        log.Fatal(err)
    }

    createTableSQL := `CREATE TABLE IF NOT EXISTS game_records (
        "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,		
        "username" TEXT,
        "score" INTEGER,
        "difficulty" INTEGER,
        "time" TEXT
    );`

    _, err = db.Exec(createTableSQL)
    if err != nil {
        log.Fatal(err)
    }
}

func saveGameRecord(w http.ResponseWriter, r *http.Request) {
    var record GameRecord
    err := json.NewDecoder(r.Body).Decode(&record)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    insertSQL := `INSERT INTO game_records (username, score, difficulty, time) VALUES (?, ?, ?, ?)`
    _, err = db.Exec(insertSQL, record.Username, record.Score, record.Difficulty, record.Time)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusOK)
}

func getGameRecords(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query("SELECT username, score, difficulty, time FROM game_records")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer rows.Close()

    var records []GameRecord
    for rows.Next() {
        var record GameRecord
        err := rows.Scan(&record.Username, &record.Score, &record.Difficulty, &record.Time)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        records = append(records, record)
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(records)
}

func main() {
    initDB()
    defer db.Close()

    // 静态文件托管
    staticDir := "../fore"
    fs := http.FileServer(http.Dir(staticDir))
    http.Handle("/", fs)

    // API 路由
    http.HandleFunc("/save", saveGameRecord)
    http.HandleFunc("/records", getGameRecords)

    fmt.Println("Server started at :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}